package com.tongda.core.repository;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tongda.core.utils.DBHelper;
import com.tongda.core.utils.DishUtil;
import com.tongda.core.utils.MenuDBHelper;
import com.tongda.core.vo.Dish;
import com.tongda.core.vo.DishesPic;
import com.tongda.core.vo.DishesSetDishes;
import com.tongda.core.vo.DishesSetDishesReplace;

/**
 * 用于维护电子菜谱购物车本地数据的类
 * 
 */
public class MenuCartDao {

	private static MenuCartDao instance;
	private MenuDBHelper dbHelper;
	private SQLiteDatabase db;
	private String TABLE_NAME = "menu_cart";

	public MenuCartDao(Context context) {
		this.dbHelper = MenuDBHelper.getInstance(context);
	}

	public static synchronized MenuCartDao getInstance(Context context) {
		if (instance == null) {
			instance = new MenuCartDao(context);
		}
		return instance;
	}

	/**
	 * 购物车中 新增菜谱
	 */
	public void insert(Dish dish, DishUtil dish_util, String tableName,
			Context context) {
		db = dbHelper.openDatabase();
		ContentValues values = new ContentValues();
		values.put("id", dish.getDishesId());
		values.put("categoryId", dish.getCategoryId());
		values.put("price", dish.getPrice() + "");
		values.put("name", dish.getDishesName());
		values.put("dishescode", dish.getDishesCode());
		values.put("salenum", dish.getSaleNum());
		values.put("unitname", dish.getUnitName());
		values.put("isset", dish.getIsSet());
		values.put("isRecommend", dish.getIsRecommend());
		values.put("recommendDesc", dish.getRecommendDesc());
		values.put("isSpecialty", dish.getIsSpecialty());
		values.put("specialtyDesc", dish.getSpecialtyDesc());
		values.put("memberPrice", dish.getMemberPrice() + "");
		values.put("specialPrice", dish.getSpecialPrice() + "");

		// 将套餐内的菜肴资源以及可替换菜肴写入数据库
		List<DishesSetDishes> dsDishes = dish.getDsDishes();
		String dsDishesArrayStr = dish_util.dsDishes2JsonStr(dsDishes);
		values.put("dsDishes", dsDishesArrayStr);

		// 把从网络获取的图片资源取其中的地址重组成jsonarr写入数据库中
		List<DishesPic> pics = dish.getDisImgs();
		String picStr = dish_util.pics2JsonStr(pics);
		values.put("url", picStr);

		values.put("dishesTasteStr", dish.getDishesTasteStr());
		values.put("pungentLevel", dish.getPungentLevel());
		values.put("isStopSell", dish.getIsStopSell());
		values.put("isRulingPrice", dish.getIsRulingPrice());
		if (dish.getIsRulingPrice() != null
				&& dish.getIsRulingPrice().equals("1")) {
			values.put("rulingPrice", dish.getPrice() + "");
		}
		values.put("dishesStyleStr", dish.getDishesStyleStr());
		values.put("dishesMaterialStr", dish.getDishesMaterialStr());
		values.put("estimate", dish.getEstimate());
		values.put("ordersalenum", dish.getOrdersalenum());
		values.put("dishesStatus", "0");
		values.put("ladu_value", 0);
		if (dbHelper == null) {
			dbHelper = MenuDBHelper.getInstance(context);
		}
		db.insert(tableName, null, values);
		dbHelper.closeDatabase();
	}

	public ArrayList<String> getOrderedIds() {
		ArrayList<String> orderedIds = new ArrayList<String>();
		try {
			db = dbHelper.openDatabase();
			Cursor cursor = db.rawQuery("select id from " + TABLE_NAME, null);
			while (cursor.moveToNext()) {
				String id = cursor.getString(cursor.getColumnIndex("id"));
				orderedIds.add(id);
			}
			cursor.close();
			dbHelper.closeDatabase();
		} catch (Exception e) {
		}
		return orderedIds;
	}

	/**
	 * 获取所有购物车中菜品（两种方式获取，一种是正常获取，一种是给各道菜肴备注的时候用的）
	 */
	public List<Dish> getAll(String dishFrom) {
		List<Dish> orderedDished = new ArrayList<Dish>();
		db = dbHelper.openDatabase();
		Cursor cursor = null;
		if (dishFrom.equals("all")) {
			cursor = db.rawQuery("select * from " + TABLE_NAME, null);
			orderedDished = getCursorDishes(cursor);
		}
		if (dishFrom.equals("unorder")) {
			cursor = db.rawQuery("select * from " + TABLE_NAME
					+ " where dishesStatus='0'", null);
			orderedDished = getCursorDishes(cursor);
		}
		cursor.close();
		dbHelper.closeDatabase();
		return orderedDished;
	}

	/**
	 * 获取购物车中有效的（不包括已退菜）菜品的总数量
	 */
	public int getEffectiveCount() {
		int totalNum = 0;
		db = dbHelper.openDatabase();
		Cursor cursor = db.rawQuery(
				"select * from menu_cart where dishesStatus!='2'", null);
		while (cursor.moveToNext()) {
			int orderSaleNum = cursor.getInt(cursor
					.getColumnIndex("ordersalenum"));
			totalNum = totalNum + orderSaleNum;
		}

		cursor.close();
		dbHelper.closeDatabase();
		return totalNum;
	}

	/**
	 * 获取购物车中菜品的总条数
	 */
	public String getCount() {
		db = dbHelper.openDatabase();
		Cursor cursor = db.rawQuery("select * from menu_cart", null);
		int num = cursor.getCount();
		cursor.close();
		dbHelper.closeDatabase();
		return String.valueOf(num);
	}

	/**
	 * 更改购物车表格中某个菜肴的备注相关列的值
	 */
	public void update(String dishId, String dishesTastesIdArr,
			String dishesTastesNameArr, String dishesAvoidfoodIdArr,
			String dishesAvoidfoodNameArr, int ladu_value, String beizhu) {
		db = dbHelper.openDatabase();
		ContentValues values = new ContentValues();
		values.put("tasteIdArray", dishesTastesIdArr);
		values.put("tasteNameArray", dishesTastesNameArr);
		values.put("avoidfoodIdArray", dishesAvoidfoodIdArr);
		values.put("avoidfoodNameArray", dishesAvoidfoodNameArr);
		values.put("ladu_value", ladu_value);
		values.put("billnotes", beizhu);
		db.update("menu_cart", values, "_id =?", new String[] { dishId });
		dbHelper.closeDatabase();
	}

	/**
	 * 获取符合cursor条件的所有菜肴
	 * 
	 * @param cursor
	 */
	public static List<Dish> getCursorDishes(Cursor cursor) {
		List<Dish> dishes = new ArrayList<Dish>();
		while (cursor.moveToNext()) {
			Dish dish = new Dish();
			int _id = cursor.getInt(cursor.getColumnIndex("_id"));
			String id = cursor.getString(cursor.getColumnIndex("id"));
			String categoryId = cursor.getString(cursor
					.getColumnIndex("categoryId"));
			BigDecimal price = new BigDecimal(cursor.getString(cursor
					.getColumnIndex("price")));
			String name = cursor.getString(cursor.getColumnIndex("name"));
			String dishescode = cursor.getString(cursor
					.getColumnIndex("dishescode"));
			float salenum = Float.valueOf(cursor.getString(cursor
					.getColumnIndex("salenum")));
			String unitname = cursor.getString(cursor
					.getColumnIndex("unitname"));
			String isset = cursor.getString(cursor.getColumnIndex("isset"));
			String isRecommend = cursor.getString(cursor
					.getColumnIndex("isRecommend"));
			String recommendDesc = cursor.getString(cursor
					.getColumnIndex("recommendDesc"));
			String isSpecialty = cursor.getString(cursor
					.getColumnIndex("isSpecialty"));
			String specialtyDesc = cursor.getString(cursor
					.getColumnIndex("specialtyDesc"));
			String memberPriceStr = cursor.getString(cursor
					.getColumnIndex("memberPrice"));
			BigDecimal memberPrice = null;
			if (!memberPriceStr.equals("null")) {
				memberPrice = new BigDecimal(memberPriceStr);
			}
			String specialPriceStr = cursor.getString(cursor
					.getColumnIndex("specialPrice"));
			BigDecimal specialPrice = null;
			if (!specialPriceStr.equals("null")) {
				specialPrice = new BigDecimal(specialPriceStr);
			}

			/*
			 * 获取图片资源
			 */
			String urlJson = cursor.getString(cursor.getColumnIndex("url"));
			List<String> picUrls = new ArrayList<String>();
			JSONArray picArrays;
			try {
				picArrays = new JSONArray(urlJson);
				for (int i = 0; i < picArrays.length(); i++) {
					JSONObject object = picArrays.getJSONObject(i);
					picUrls.add(object.getString("picUrl"));
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			/*
			 * 获取套餐资源
			 */
			String dsDishesStr = cursor.getString(cursor
					.getColumnIndex("dsDishes"));
			List<DishesSetDishes> dsDishes = new ArrayList<DishesSetDishes>();
			try {
				JSONArray dsDishesArray = new JSONArray(dsDishesStr);
				for (int i = 0; i < dsDishesArray.length(); i++) {
					DishesSetDishes dsDish = new DishesSetDishes();
					JSONObject dsDishObject = dsDishesArray.getJSONObject(i);
					dsDish.setDsDishesId(dsDishObject.getString("dsDishesId"));
					dsDish.setMr_dishesId(dsDishObject.getString("mr_dishesId"));
					dsDish.setMr_dishesName(dsDishObject
							.getString("mr_dishesName"));
					dsDish.setMr_dishesCode(dsDishObject
							.getString("mr_dishesCode"));
					dsDish.setMr_unitNum(dsDishObject.getString("mr_unitNum"));
					dsDish.setMr_unitName(dsDishObject.getString("mr_unitName"));

					dsDish.setDishesId(dsDishObject.getString("dishesId"));
					dsDish.setDishesName(dsDishObject.getString("dishesName"));
					dsDish.setDishesCode(dsDishObject.getString("dishesCode"));
					dsDish.setUnitNum(dsDishObject.getString("unitNum"));
					dsDish.setUnitName(dsDishObject.getString("unitName"));
					// 处理可替换菜肴
					List<DishesSetDishesReplace> dishesSetDishesReplaces = new ArrayList<DishesSetDishesReplace>();
					String dsReplaceStr = dsDishObject
							.getString("dishesSetDishesReplaces");
					ObjectMapper objectmapper = new ObjectMapper();
					DishesSetDishesReplace[] temp = objectmapper.readValue(
							dsReplaceStr, DishesSetDishesReplace[].class);
					dishesSetDishesReplaces = Arrays.asList(temp);
					dsDish.setDishesSetDishesReplaces(dishesSetDishesReplaces);
					dsDishes.add(dsDish);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			String dishesTasteStr = cursor.getString(cursor
					.getColumnIndex("dishesTasteStr"));
			String pungentLevel = cursor.getString(cursor
					.getColumnIndex("pungentLevel"));
			String isStopSell = cursor.getString(cursor
					.getColumnIndex("isStopSell"));
			String isRulingPrice = cursor.getString(cursor
					.getColumnIndex("isRulingPrice"));
			String dishesStyleStr = cursor.getString(cursor
					.getColumnIndex("dishesStyleStr"));
			String dishesMaterialStr = cursor.getString(cursor
					.getColumnIndex("dishesMaterialStr"));

			String tasteIdArray = cursor.getString(cursor
					.getColumnIndex("tasteIdArray"));
			String tasteNameArray = cursor.getString(cursor
					.getColumnIndex("tasteNameArray"));
			String avoidfoodIdArray = cursor.getString(cursor
					.getColumnIndex("avoidfoodIdArray"));
			String avoidfoodNameArray = cursor.getString(cursor
					.getColumnIndex("avoidfoodNameArray"));
			int ladu_value = cursor.getInt(cursor.getColumnIndex("ladu_value"));
			String billnotes = cursor.getString(cursor
					.getColumnIndex("billnotes"));
			int ordersalenum = cursor.getInt(cursor
					.getColumnIndex("ordersalenum"));
			String dishesStatus = cursor.getString(cursor
					.getColumnIndex("dishesStatus"));
			String dinerBillDisheId = cursor.getString(cursor
					.getColumnIndex("dinerBillDisheId"));
			String rulingPrice = cursor.getString(cursor
					.getColumnIndex("rulingPrice"));

			dish.set_id(_id);
			dish.setDishesId(id);
			dish.setCategoryId(categoryId);
			dish.setPrice(price);
			dish.setDishesName(name);
			dish.setDishesCode(dishescode);
			dish.setSaleNum(salenum);
			dish.setUnitName(unitname);
			dish.setIsSet(isset);
			dish.setIsRecommend(isRecommend);
			dish.setRecommendDesc(recommendDesc);
			dish.setIsSpecialty(isSpecialty);
			dish.setSpecialtyDesc(specialtyDesc);
			dish.setMemberPrice(memberPrice);
			dish.setSpecialPrice(specialPrice);
			dish.setPicUrls(picUrls);
			dish.setDsDishes(dsDishes);
			dish.setDishesTasteStr(dishesTasteStr);
			dish.setPungentLevel(pungentLevel);
			dish.setIsStopSell(isStopSell);
			dish.setIsRulingPrice(isRulingPrice);
			dish.setDishesStyleStr(dishesStyleStr);
			dish.setDishesMaterialStr(dishesMaterialStr);

			dish.setTasteIdArray(tasteIdArray);
			dish.setTasteNameArray(tasteNameArray);
			dish.setAvoidfoodIdArray(avoidfoodIdArray);
			dish.setAvoidfoodNameArray(avoidfoodNameArray);
			dish.setLadu_value(ladu_value);
			dish.setBillnotes(billnotes);
			dish.setOrdersalenum(ordersalenum);
			dish.setDishesStatus(dishesStatus);
			dish.setDinerBillDisheId(dinerBillDisheId);
			dish.setRulingPrice(rulingPrice);
			dishes.add(dish);
		}
		return dishes;
	}

	/**
	 * 清空当前菜谱
	 */
	public void clearOrderDish() {
		try {
			db = dbHelper.openDatabase();
			String checkSql = "SELECT name FROM sqlite_master WHERE type='table' and name='menu_cart'";
			Cursor cursor = db.rawQuery(checkSql, null);
			if (cursor.getCount() > 0) {
				// 调试阶段暂时都清空 因为表结构经常变化
				db.execSQL("drop table menu_cart");
				db.execSQL(MenuDBHelper.MENU_CART_TABLE_CREATE);
			} else {
				db.execSQL(MenuDBHelper.MENU_CART_TABLE_CREATE);
			}
			String sql = "delete from menu_cart;";
			db.execSQL(sql);
			dbHelper.closeDatabase();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 更改购物车中某个菜肴的已点数量
	 */
	public void updateNum(String dishId, int num) {
		db = dbHelper.openDatabase();
		ContentValues values = new ContentValues();
		values.put("ordersalenum", num);
		db.update("menu_cart", values, "id =?", new String[] { dishId });
		dbHelper.closeDatabase();
	}

	/**
	 * 获得购物车中某个菜肴的已点数量
	 */
	public int getNum(String dishId) {
		int num = 0;
		db = dbHelper.openDatabase();
		Cursor cursor = db.rawQuery("select * from menu_cart where id=?",
				new String[] { dishId });
		if (cursor.moveToNext()) {
			num = cursor.getInt(cursor.getColumnIndex("ordersalenum"));
		}
		cursor.close();
		dbHelper.closeDatabase();
		return num;
	}

	/**
	 * 处理来一份的时候购物车中某个菜肴的数量的自加
	 */
	public void jiaorerdishesNum(String dishId) {
		db = dbHelper.openDatabase();
		int num = 0;
		if (dishId != null) {
			Cursor cursor = db.rawQuery("select * from " + TABLE_NAME
					+ " where id=?", new String[] { dishId });
			if (cursor.moveToNext()) {
				num = cursor.getInt(cursor.getColumnIndex("ordersalenum"));
			}
		}
		num++;
		ContentValues values = new ContentValues();
		values.put("ordersalenum", num);
		db.update(TABLE_NAME, values, "id =?", new String[] { dishId });
		dbHelper.closeDatabase();
	}

	/**
	 * 删除购物车中选中的菜肴（根据唯一主键_id）
	 */
	public void deleteOrderDish(int _id) {
		String _idStr = String.valueOf(_id);
		db = dbHelper.openDatabase();
		db.delete(TABLE_NAME, "_id=?", new String[] { _idStr });
		dbHelper.closeDatabase();
	}

	/**
	 * 获取购物车中所有菜肴的菜类id
	 */
	public ArrayList<String> getdcIds() {
		ArrayList<String> dcIds = new ArrayList<String>();
		try {
			db = dbHelper.openDatabase();
			Cursor cursor = db.rawQuery("select * from " + TABLE_NAME, null);
			while (cursor.moveToNext()) {
				String id = cursor.getString(cursor
						.getColumnIndex("categoryId"));
				int ordernum = cursor.getInt(cursor
						.getColumnIndex("ordersalenum"));
				for (int i = 0; i < ordernum; i++) {
					dcIds.add(id);
				}
			}
			cursor.close();
			dbHelper.closeDatabase();
		} catch (Exception e) {
		}
		return dcIds;
	}

	/**
	 * 更改购物车中已点菜肴的份数列的值
	 */
	public void updateOrdishesNum(String _id, String numStr) {
		db = dbHelper.openDatabase();
		ContentValues values = new ContentValues();
		values.put("ordersalenum", Float.valueOf(numStr));
		db.update(TABLE_NAME, values, "_id=?", new String[] { _id });
		dbHelper.closeDatabase();
	}

	/**
	 * 更改购物车中套餐替换后的套餐列的值
	 */
	public void updateOrdishesdsDishes(String _id, String dsDishesStr) {
		db = dbHelper.openDatabase();
		ContentValues values = new ContentValues();
		values.put("dsDishes", dsDishesStr);
		db.update(TABLE_NAME, values, "_id=?", new String[] { _id });
		dbHelper.closeDatabase();
	}

	/**
	 * 将账单菜肴id存入字段
	 */
	public void addBillDisheId(String _id, String dinerBillDisheId) {
		db = dbHelper.openDatabase();
		ContentValues values = new ContentValues();
		values.put("dinerBillDisheId", dinerBillDisheId);
		db.update(TABLE_NAME, values, "_id =?", new String[] { _id });
		dbHelper.closeDatabase();
	}

	/**
	 * 更改购物车中加入账单菜肴的状态列为已下单
	 */
	public void updateDishStatus(String _id, String dishStatus) {
		db = dbHelper.openDatabase();
		ContentValues values = new ContentValues();
		values.put("dishesStatus", dishStatus);
		db.update(TABLE_NAME, values, "_id =?", new String[] { _id });
		dbHelper.closeDatabase();
	}

	/**
	 * 更改购物车中时价菜的时价价格
	 */
	public void updaterulingPrice(String _id, String price) {
		db = dbHelper.openDatabase();
		ContentValues values = new ContentValues();
		values.put("rulingPrice", price);
		db.update(TABLE_NAME, values, "_id =?", new String[] { _id });
		dbHelper.closeDatabase();
	}

	/**
	 * 判断购物车数据库中是否有未下单的菜肴
	 * 
	 * @param dishId
	 */
	public boolean isExistunOrderedDish() {
		boolean result = false;
		db = dbHelper.openDatabase();
		Cursor cursor = db.rawQuery("select _id from " + TABLE_NAME
				+ " where dishesStatus='0'", null);
		result = cursor.moveToNext();
		cursor.close();
		dbHelper.closeDatabase();
		return result;
	}

	/**
	 * 判断购物车数据库中是否都是未下单的菜肴
	 * 
	 * @param dishId
	 */
	public boolean isunAllunOrderedDish() {
		boolean result = false;
		db = dbHelper.openDatabase();
		Cursor cursor = db.rawQuery("select _id from " + TABLE_NAME
				+ " where dishesStatus in('1','2')", null);
		result = cursor.moveToNext();
		cursor.close();
		dbHelper.closeDatabase();
		return result;
	}
}
